<template>
    <div class="app-container">
        <levelbar></levelbar>
        <div class="form-box" v-loading='loading'>
            <div class="form-title">学生信息</div>
            <el-form :model="dataForm" :rules="rules" ref="dataForm" label-width="80px" class="form" label-position='right'>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">基本信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="学生姓名" prop="studentName" :rules="rules.studentName">
                                    <el-popover
                                    placement="top-start"
                                    trigger="focus" 
                                    content="长度在12个字符以内。">
                                        <el-input v-model="dataForm.studentName" slot="reference" :maxlength="12" style="width:95%;" ></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="性别" prop="studentSex" :rules="rules.studentSex">
                                    <el-radio-group v-model="dataForm.studentSex">
                                        <el-radio label="0">男</el-radio>
                                        <el-radio label="1">女</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="学籍号" prop="schoolrollCode" :rules="rules.schoolrollCode">
                                    <el-popover
                                    placement="top-start"
                                    trigger="focus" 
                                    content="长度在20个字符以内。">
                                        <el-input v-model="dataForm.schoolrollCode" slot="reference" :maxlength="20" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="e学云ID号" prop="eCode" :rules="rules.eCode"> 
                                    <span>{{dataForm.eCode}}</span>
                                    <!-- <el-input v-model="dataForm.eCode" style="width:95%;" disabled></el-input>     -->
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <!-- <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="关联家长数">
                                    <span>{{dataForm.relevanceParentNum}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row> -->
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">家长信息</span>
                    </div>
                    <!-- <div v-if="dataForm.parentInfo.length == '0'" class="form-content item">暂无家长信息</div> -->
                    <div class="form-content item" v-for="(item, index) in dataForm.parentInfo" :key="item.eCode">
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item :label="'联系人 ' + (index + 1)" :prop="'parentInfo.' + index + '.phone'" :rules="rules.contactPhone">
                                    <!-- <span>{{item.phone}}</span> -->
                                    <el-popover
                                    placement="top-start"
                                    trigger="focus" 
                                    content="长度在11个字符以内。">
                                        <el-input v-model="item.phone" slot="reference" style="width:95%;" :disabled="item.eCode" :maxlength="11"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="1"  v-if="!item.eCode">
                                <el-button type="text" class="delBtn" @click="removeContactWay(index, item)"><i class="el-icon-delete"></i></el-button>
                            </el-col>
                            <el-col :span="11" v-if="item.eCode">
                                <el-row :gutter="21">
                                    <el-col :span="6">
                                        <el-form-item label="姓名">
                                            <span>{{item.parentName}}</span>
                                            <!-- <el-input v-model="item.parentName" style="width:95%;" disabled></el-input> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="6">
                                        <el-form-item label="关系">
                                            <span>{{item.relationship}}</span>
                                            <!-- <el-input v-model="item.relationship" style="width:95%;" disabled></el-input> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="e学云ID号">
                                            <span>{{item.eCode}}</span>
                                            <!-- <el-input v-model="item.eCode" style="width:95%;" disabled></el-input> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="4" class="un-bind">
                                        <el-button type="text" class="btn-success btn-unbind" @click="unBind(item)">解绑</el-button>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </div>
                    <el-button v-if="dataForm.parentInfo.length < 5" type="text" @click="addContactWay" class="addBtn btn-success"><i class="el-icon-plus"></i> 继续添加</el-button>
                </div>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">身份信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="出生年月">
                                    <el-date-picker
                                    :editable='false'
                                    v-model="dataForm.birthDay"
                                    type="date"
                                    placeholder="选择日期"
                                    style="width:95%;"
                                    :picker-options="pickerOptions">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="户口性质">
                                    <el-select v-model="dataForm.accountsNatureId" placeholder="请选择" style="width:95%;">
                                        <el-option v-for="obj in accountsNatureList" :key="obj.accountNatureId" :label="obj.accountNatureName" :value="obj.accountNatureId"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="省" prop="provinceName" :rules="rules.provinceName">
                                    <province v-model="dataForm.provinceName" @getProvinceName='getProvinceName' style="width:95%;"></province>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="市" prop="cityName" :rules="rules.provinceName">
                                    <city v-model="dataForm.cityName" :province="dataForm.provinceName" @getCityName='getCityName' style="width:95%;"></city>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="区" prop="areaName" :rules="rules.provinceName">
                                    <region v-model="dataForm.areaName" :city="dataForm.cityName" @getAreaName='getAreaName' style="width:95%;"></region>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-item-title">
                        <!-- <span class="note-css"></span> -->
                        <span class="title-level">其他信息</span>
                    </div>
                    <div class="form-content">
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="电子邮箱" prop="email" :rules="rules.emailAddress">
                                    <el-popover
                                    placement="top-start"
                                    trigger="focus" 
                                    content="长度在32个字符以内。">
                                        <el-input v-model="dataForm.email" slot="reference" :maxlength="32" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="邮政编码" prop="postalCode" :rules="rules.postalcode">
                                    <el-popover
                                    placement="top-start"
                                    trigger="focus" 
                                    content="请输入6位数字。">
                                        <el-input v-model="dataForm.postalCode" slot="reference" :maxlength="6" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="12">
                                <el-form-item label="考勤卡号" prop="workCode" :rules="rules.cardNum">
                                    <el-input v-model="dataForm.workCode" style="width:95%;"></el-input>
                                </el-form-item>
                            </el-col> -->
                        </el-row>
                        <el-row :gutter="21">
                            <el-col :span="12">
                                <el-form-item label="现住址" prop="presentAddress" :rules="rules.currentAddress">
                                    <el-popover
                                    placement="top-start"
                                    trigger="focus" 
                                    content="长度在30个字符以内。">
                                        <el-input v-model="dataForm.presentAddress" slot="reference" :maxlength="30" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="家庭地址" prop="homeAddress" :rules="rules.currentAddress">
                                    <el-popover
                                    placement="top-start"
                                    trigger="focus" 
                                    content="长度在30个字符以内。">
                                        <el-input v-model="dataForm.homeAddress" slot="reference" :maxlength="30" style="width:95%;"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <div class="form-item">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item>
                                <div class="footer">
                                    <el-button @click="resetForm('dataForm')">取消</el-button>
                                    <el-button type="primary" @click="submitForm('dataForm')">确认</el-button>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
    import { isEmpty } from 'utils/validate';
    import moment from 'moment';
    import Levelbar from '../../layout/Levelbar';
    import province from 'components/CascadeRegion/province';
    import city from 'components/CascadeRegion/city';
    import region from 'components/CascadeRegion/region';
    import { getStudentRelativeInfo, updateLookStudentInfo, getAccountsNatureInfo, relieveStudentParentRelative, removeStudentPhoneMap } from 'api/studentMange';
    import validate from '@/utils/validate';
    let dataForm = {
        accountsNature: '',
        accountsNatureId: '',
        areaName: '',
        birthDay: '',
        cityName: '',
        eCode: '',
        email: '',
        homeAddress: '',
        parentInfo: [{
            parentName: '', 
            relationship: '', 
            phone: '',
            eCode: ''
        }],
        phone: '',
        postalCode: '',
        presentAddress: '',
        provinceName: '',
        schoolrollCode: '',
        studentName: '',
        studentSex: '',
        workCode: ''
    };

    export default {
        name: 'studentInforPage',
        components: { Levelbar, province, city, region },
        data() {
            const validateEmpty = (rule, value, callback) => {
                if (!isEmpty(value)) {
                    callback(new Error('内容中不能存在空格'));
                } else {
                    callback();
                }
            };
            return {
                loading: false,
                provinceName: '',
                cityName: '',
                areaName: '',
                dataForm,
                dataList: null,
                accountsNatureList: [],
                pickerOptions: {
                    disabledDate(time) {
                        return (time.getTime()) > (Date.now() - 3600 * 1000 * 24);
                    }
                },
                rules: {

                    // 基本信息：
                    studentName: [
                        { required: true, message: '请输入学生姓名', trigger: 'blur' },
                        { required: true, trigger: 'blur', validator: validateEmpty },
                        { min: 1, max: 12, message: '长度在12个字符以内', trigger: 'blur' }
                    ],
                    birthday: [
                        { min: 1, max: 10, message: '长度在10个字符以内', trigger: 'blur' }
                    ],
                    contactPhone: [
                        ...validate.phone()
                    ],
                    // 家长信息
                    contactWay: [
                        ...validate.phone()
                    ],
                    provinceName: [
                        { required: true, message: '请选择', trigger: 'blur' },
                    ],

                    // 其他信息
                    emailAddress: [
                        { min: 1, max: 32, message: '长度在32个字符以内'},
                        { pattern: /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/, message: '请输入正确的电子邮箱', trigger: 'blur' }
                    ],
                    postalcode: [
                        { pattern: /^\d{6}/, message: '请输入6位数字', trigger: 'blur' }
                    ],
                    cardNum: [
                        { min: 1, max: 32, message: '长度在32个字符以内', trigger: 'blur' }
                    ],
                    currentAddress: [
                        { min: 1, max: 30, message: '长度在30个字符以内', trigger: 'blur' }
                    ],
                    schoolrollCode: [
                        { pattern: /^[A-Za-z0-9]+$/, message: '只允许输入数字和字母'},
                        { min: 1, max: 20, message: "长度在20个字符以内", trigger: "blur" }
                    ]
                }
            }
        },
        created() {
            this.getAccountsNatureFu();
            this.showStudentInfor();
        },
        methods: {
            addContactWay() {
                this.dataForm.parentInfo.push({
                    phone: ''
                });
            },
            removeContactWay(index, item) {
                if (index !== -1) {
                    this.dataForm.parentInfo.splice(index, 1);
                }
                let status = item.status;
                let studentId = this.$route.params.studentId;
                let phone = item.phone;  
                if(phone&&status) {
                    this.loading = true;
                    removeStudentPhoneMap(status, studentId, phone).then(res => {
                        this.loading = false;
                        this.$message.success(res.data.errorMsg);
                    }).catch(() => {
                        this.loading = false;
                    });
                }
            },
            showStudentInfor() {
                let studentId = this.$route.params.studentId;
                getStudentRelativeInfo(studentId).then(response => {
                    if (response.data.content) {
                        this.dataForm = response.data.content;
                        if(!this.dataForm.provinceName) {
                            this.dataForm.provinceName = '';
                        }
                        if(!this.dataForm.cityName) {
                            this.dataForm.cityName = '';
                        }
                        if(!this.dataForm.areaName) {
                            this.dataForm.areaName = '';
                        }
                    }
                }).catch(() => {
                    this.loading = false;
                });
            },
            submitForm(dataForm) {
                let phoneArray = [];
                this.dataForm.parentInfo.forEach(item => {
                    if(item.phone) {
                        phoneArray.push(item.phone);
                    }
                });
                const items = new Set(phoneArray);
                if(items.size != phoneArray.length) {
                    this.$message.error('联系人号码重复');
                    return;
                }
                this.$refs[dataForm].validate((valid) => {
                    if (valid) {
                        let phoneList = [];
                        if(this.dataForm.parentInfo.length) {
                            this.dataForm.parentInfo.forEach(item => {
                                if(item.phone) {
                                    phoneList.push(item.phone);
                                }
                            });
                        }
                        
                        let studentId = this.$route.params.studentId; // 学生id
                        let studentName = this.dataForm.studentName; // 学生姓名
                        let studentSex = this.dataForm.studentSex; // 学生性别
                        let schoolrollCode = this.dataForm.schoolrollCode; // 学籍号
                        let birthDay = !this.dataForm.birthDay?'':moment(this.dataForm.birthDay).format('YYYY-MM-DD'); // 出生年月
                        let accountNature = this.dataForm.accountsNatureId; // 户口性质
                        let provinceId = this.dataForm.provinceName; // 学生所属省id
                        let cityId = this.dataForm.cityName; // 学生所属市id
                        let areaId = this.dataForm.areaName; // 学生所属区id
                        let provinceName = this.provinceName; // 省名称
                        let cityName = this.cityName; // 市名称
                        let areaName = this.areaName; // areaName
                        let email = this.dataForm.email; // 电子邮箱
                        let phones = phoneList; // 手机
                        let postalCode = this.dataForm.postalCode; // 邮政编码
                        let workCode = this.dataForm.workCode; // 考勤卡号（暂时没有）
                        let presentAddress = this.dataForm.presentAddress; // 现住地址
                        let homeAddress = this.dataForm.homeAddress; // 家庭地址
                        this.loading = true;
                        updateLookStudentInfo(
                            studentId, // 学生id
                            studentName, // 学生姓名
                            studentSex, // 学生性别
                            schoolrollCode, // 学籍号
                            birthDay, // 出生年月
                            accountNature, // 户口性质
                            provinceId, // 学生所属省id
                            cityId, // 学生所属市id
                            areaId, // 学生所属区id
                            provinceName, // 省名称
                            cityName, // 市名称
                            areaName, // areaName
                            email, // 电子邮箱
                            postalCode, // 邮政编码
                            workCode, // 考勤卡号（暂时没有）
                            presentAddress, // 现住地址
                            homeAddress, // 家庭地址
                            phones
                        ).then(response => {
                            this.loading = false;
                            if (response.data.status == 200) {
                                this.$message.success(response.data.errorMsg);
                                if(this.$route.params.classObj) {
                                    this.$router.push({ path: `/classStudent/studentList/${this.$route.params.classObj}`});
                                    this.$store.dispatch('UpdateCache', true);
                                } else {
                                    this.$router.go(-1);
                                }
                                this.$store.dispatch('UpdateCache', true); 
                            } else {
                                this.$message.error(response.data.errorMsg);
                            }
                        }).catch(() => {
                            this.loading = false;
                        })
                       
                    } else {
                        return false;
                    }
                });
            },
            resetForm(dataForm) {
                this.$refs[dataForm].resetFields();
                this.$router.go(-1);
            },

            // 户口性质
            getAccountsNatureFu() {
                getAccountsNatureInfo().then(response => {
                    this.accountsNatureList = response.data.content;
                    if (response.data.content) {
                        this.accountsNatureList.unshift({
                            accountNatureId: '',
                            accountNatureName: '请选择'
                        });
                    }
                })
            },
            getProvinceName(name) {
                this.provinceName = name;
            },
            getCityName(name) {
                this.cityName = name;
            },
            getAreaName(name) {
                this.areaName = name;
            },
            unBind(obj) {
                this.$confirm('确定解除学生与该家长关系？', '', {
                    closeOnClickModal: false,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: ' ', 
                    title: '  '
                }).then(() => {
                    let studentId = this.$route.params.studentId;
                    let parentExueCode = obj.eCode;
                    relieveStudentParentRelative(studentId, parentExueCode).then(res => {
                        this.$message.success(res.data.errorMsg);
                        this.showStudentInfor();
                    });
                }).catch((e) => {
                    this.$message.info('已取消解绑');     
                });
            }
        }
    }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .app-container {
        position: relative;
        padding: 20px 20px 10px;
        $bgcolor: #fff;

        @mixin showTitle() {
             background: $bgcolor;
            box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
            -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
        }
        .delBtn {
            font-size: 20px;
            color:#999;
        }
        .addBtn{
            margin-left:80px;
            font-size:14px;
            color:#ff5e2c;
        }
        .form-box {
            padding: 0px 50px;
            @include showTitle();
            .form-title {
                padding-top:8px;
                text-align: center;
                font-size: 18px;
                color: #333;
                // height: 78px;
                line-height: 72px;
                font-weight: bold;
                font-family: Microsoft YaHei;
                border-bottom: 1px solid #ddd;
            }
            .form {
                .form-item {
                    padding-bottom: 40px;
                    .form-item-title {
                        margin: 40px 0;
                        font-size: 14px;
                        color: #333;
                        line-height: 14px;
                        border-left: 4px solid #ff5e2c;
                        text-indent: 16px;
                        // .note-css {
                        //     vertical-align: middle;
                        //     display: inline-block;
                        //     width: 4px;
                        //     height: 14px;
                        //     margin-right: 26px;
                        //     border-left: 3px solid #ff5e2c;
                        // }
                    }
                    .form-content {
                        margin: 0 8px;
                    }
                    .item {
                        margin-bottom: 20px;
                    }
                    .back {
                        margin-top: 20px;
                    }
                    .footer {
                        text-align: center;
                        margin-top: 40px;
                    }
                    .title-way {
                        padding-right: 15px;
                    }
                    .control {
                        text-align: right;
                    }
                    .un-bind {
                        position: relative;
                        .btn-unbind {
                            position: absolute;
                            top: 6px;
                        }
                    }
                }
            }
        }
    }
</style>